package com.xxkk.spring_boot_web.sdk.WAVE;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;

public class WAVESDK {

    //获取一次性token,这个包不涉及wmt-mfs
    public static String securityToken(com.alibaba.fastjson.JSONObject header_map) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder()
                .url("https://api.wavemoney.io:8100/v3/wmt-mfs-otp/security-token")
                .get()
                .addHeader("Host", "api.wavemoney.io")
                .addHeader("User-Agent", "okhttp/4.9.0");
        header_map.getInnerMap().forEach((key, value) -> builder.addHeader(key, (String) value));

        Request request = builder.build();
        Response response = client.newCall(request).execute();
        String result = response.body().string();
        JSONObject jsonObject = new JSONObject(result);
        String s = jsonObject.getJSONObject("responseMap").getString("securityCounter");
        return s;
    }

    /**
     * 发送验证码
     */
    public static String generateOtp(String phone, com.alibaba.fastjson.JSONObject header) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder()
                .url("https://api.wavemoney.io:8100/v3/wmt-mfs-otp/generate-otp?msisdn=" + phone)
                .get()
                .addHeader("Host", "api.wavemoney.io")
                .addHeader("User-Agent", "okhttp/4.9.0")
                .addHeader("Accept-Encoding", "application/json");
        header.getInnerMap().forEach((key, value) -> builder.addHeader(key, (String) value));
//                .addHeader("device", header.getString("device"))
//                .addHeader("cpuabi", cpuabi)
//                .addHeader("manufacturer", manufacturer)
//                .addHeader("model", model)
//                .addHeader("product", product)
//                .addHeader("osversion", osversion)
//                .addHeader("appid", appid)
//                .addHeader("appversion", appversion)
//                .addHeader("versioncode", versioncode)
//                .addHeader("deviceid", deviceid)
//                .addHeader("userlanguage", userlanguage);

        Request request = builder.build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    //提交验证码
    public static String confirmOtp(String phone, String otp, com.alibaba.fastjson.JSONObject header) throws IOException {
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "msisdn=" + phone + "&otp=" + otp);
        Request.Builder builder = new Request.Builder()
                .url("https://api.wavemoney.io:8100/v3/wmt-mfs-otp/confirm-otp")
                .post(body)
                .addHeader("Host", "api.wavemoney.io")
                .addHeader("User-Agent", "okhttp/4.9.0")
                .addHeader("Accept-Encoding", "application/json")
                .addHeader("Content-Type", "application/x-www-form-urlencoded");
        header.getInnerMap().forEach((key, value) -> builder.addHeader(key, (String) value));

        Request request = builder.build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    //登陆
    public static ApiResponse login(String phone, String pin, String s1, String s2, String notificationtrackingid, com.alibaba.fastjson.JSONObject header_map) throws Exception {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String param = "msisdn=" + phone + "&password=" + URLEncoder.encode(Utils.rsaEncrypt(pin + ":" + s1)) + "&pin=" + URLEncoder.encode(Utils.rsaEncrypt(pin + ":" + s2));
        System.out.println("Login param => " + param);

        RequestBody body = RequestBody.create(mediaType, param);
        Request.Builder builder = new Request.Builder()
                .url("https://api.wavemoney.io:8100/v3/mfs-customer/login")
                .post(body)
                .addHeader("Host", "api.wavemoney.io")
                .addHeader("User-Agent", "okhttp/4.9.0")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("notificationtrackingid", notificationtrackingid);
        header_map.getInnerMap().forEach((key, value) -> builder.addHeader(key, (String) value));

        Request request = builder.build();
        Response response = client.newCall(request).execute();
        ApiResponse apiResponse = new ApiResponse(
                response.code(),
                response.body().string(),
                response.headers().get("wmt-mfs")
        );
        return apiResponse;
    }

    //转账记录
    public static ApiResponse histories(String wmt_mfs, com.alibaba.fastjson.JSONObject header_map, String url) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder()
                //条数能随便改，参数能随便加随便拼接
                //通用，限制条数：https://api.wavemoney.io:8100/v3/mfs-customer/tnxhistory-utility/tnx-histories?limit=20&offset=0
                //限制金额：https://api.wavemoney.io:8100/v3/mfs-customer/tnxhistory-utility/tnx-histories?limit=20&offset=0&maxAmount=20&minAmount=2
                //限制日期：https://api.wavemoney.io:8100/v3/mfs-customer/tnxhistory-utility/tnx-histories?limit=20&offset=0&startDate=2024-10-07&endDate=2025-01-05
                //查询订单详细: https://api.wavemoney.io:8100/v3/mfs-customer/tnxhistory-utility/tnx-history-detail?transId=365007579&transDate=2025-01-07
                .url(url)
                .get()
                .addHeader("Host", "api.wavemoney.io")
                .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 11; HD1900 Build/RKQ1.201022.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.135 Mobile Safari/537.36")
                .addHeader("wmt-mfs", wmt_mfs)
                .addHeader("content-type", "application/json");
        header_map.getInnerMap().forEach((key, value) -> builder.addHeader(key, (String) value));

//                .addHeader("appid", "mm.com.wavemoney.wavepay")
//                .addHeader("deviceid", "2a8ace2353237e1ac4c95f268f6f757f299eaa83")
//                .addHeader("device", "OnePlus 7T(HD1900)")
//                .addHeader("versioncode", "1463")
//                .addHeader("appversion", "2.3.1")
//                .addHeader("userlanguage", "en")
//                .addHeader("osversion", "11")
//                .addHeader("product", "OnePlus7T")
        Request request = builder.build();
        Response response = client.newCall(request).execute();
        ApiResponse apiResponse = new ApiResponse(
                response.code(),
                response.body().string(),
                response.headers().get("wmt-mfs")
        );
        return apiResponse;
    }

    //核对收款账号,且获取收款名字(可以获取到保存到数据库，应该不用每一次都请求，逻辑自己完善)

    /**
     * 查询收款账号信息
     *
     * @param wmt_mfs            token
     * @param beneficiaryAccount 查询账号
     */
    public static ApiResponse checkBeneficiary(String wmt_mfs, String beneficiaryAccount,String fingerprint, com.alibaba.fastjson.JSONObject header_map) throws Exception {
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"msisdn\":\"" + beneficiaryAccount + "\"}");
        System.out.println("checkBeneficiary body => " + body.toString());
        Request.Builder builder = new Request.Builder()
                .url("https://api.wavemoney.io:8100/v2/mfs-customer/check-mfs-beneficiary")
                .post(body)
                .addHeader("User-Agent", "Dart/3.2 (dart:io)")
                .addHeader("Content-Type", "application/json")
                .addHeader("wmt-mfs", wmt_mfs)
                .addHeader("fingerprint", fingerprint);
        header_map.getInnerMap().forEach((key, value) -> builder.addHeader(key, (String) value));
//                .addHeader("appid", "mm.com.wavemoney.wavepay")
//                .addHeader("deviceid", "2a8ace2353237e1ac4c95f268f6f757f299eaa83")
//                .addHeader("appversion", "2.3.1")
//                .addHeader("userlanguage", "en")
//                .addHeader("osversion", "11")
//                .addHeader("versioncode", "1463")
//                .addHeader("device", "OnePlus 7T(HD1900)")
//                .addHeader("product", "OnePlus7T")

        Request request = builder.build();

        Response response = client.newCall(request).execute();
        ApiResponse apiResponse = new ApiResponse(
                response.code(),
                response.body().string(),
                response.headers().get("wmt-mfs")
        );
        return apiResponse;


        //逻辑自己判断
//        {
//            "responseMap":{
//            "accountStatus": [
//            "active"          // 账户状态
//    ],
//            "name":"Zaw Lin Aung",        // 收款人姓名
//            "registered":true    // 是否注册
//        },
//            "message":""
//        }
    }

    //转账
    //receiverName收款者名字, receiverMsisdns收款者账号
    //senderName转账人名字,
    //amount转账金额 , note转账备注
    public static ApiResponse sendMoney(String deviceid, String wmt_mfs, String receiverName, String receiverMsisdn, String senderName, String amount, String pin, String note, String s1) throws Exception {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String param = "receiverName=" + URLEncoder.encode(receiverName) + "&receiverMsisdn=" + receiverMsisdn + "&senderName=" + URLEncoder.encode(senderName) + "&amount=" + amount + "&pin=" + URLEncoder.encode(Utils.rsaEncrypt(pin + ":" + s1)) + "&note=" + URLEncoder.encode(note);
        System.out.println("sendMoney param => " + param);

        RequestBody body = RequestBody.create(mediaType, param);
        Request request = new Request.Builder()
                .url("https://api.wavemoney.io:8100/v2/mfs-customer/send-money-ma")
                .post(body)
                .addHeader("User-Agent", "Dart/3.2 (dart:io)")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("appid", "mm.com.wavemoney.wavepay")
                .addHeader("deviceid", deviceid)
                .addHeader("wmt-mfs", wmt_mfs)
                .build();
        Response response = client.newCall(request).execute();
        ApiResponse apiResponse = new ApiResponse(
                response.code(),
                response.body().string(),
                response.headers().get("wmt-mfs")
        );
        return apiResponse;
    }
}
